package com.publish.file.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import com.publish.file.service.auth.RoleConstant;
import com.publish.file.service.auth.SimpleAuthentication;
import com.publish.file.service.auth.UserRoleDetail;
import com.publish.file.service.jwt.JwtService;
import com.publish.file.service.jwt.Payload;
import com.publish.file.service.jwt.exception.JwtException;

public class JwtAuthFilter extends BasicAuthenticationFilter {

	public JwtAuthFilter(AuthenticationManager authenticationManager, JwtService jwtServiceImpl) {
		super(authenticationManager);
		this.jwtServiceImpl = jwtServiceImpl;
	}

	private JwtService jwtServiceImpl;
	public static final String TOKEN_KEY = "token";

	public JwtAuthFilter(AuthenticationManager authenticationManager) {
		super(authenticationManager);
	}

	public JwtAuthFilter(AuthenticationManager authenticationManager,
			AuthenticationEntryPoint authenticationEntryPoint) {
		super(authenticationManager, authenticationEntryPoint);
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String token = request.getHeader(TOKEN_KEY);
		if (token != null && !"null".equals(token)) {
			try {
				Payload payload = jwtServiceImpl.vertifyToken(token);
				if (payload != null) {
					String userName = payload.getUserName();
					UserRoleDetail userRoleDetail = new UserRoleDetail(userName, userName);
					userRoleDetail.addRole(RoleConstant.ROLE_DEV);
					SimpleAuthentication b = new SimpleAuthentication(userName, userName, userRoleDetail, payload);
					SecurityContextHolder.getContext().setAuthentication(b);
				}
			} catch (JwtException e) {
				e.printStackTrace();
			}
		} else {
			UserRoleDetail userRoleDetail = new UserRoleDetail(RoleConstant.USER_VISITOR,
					RoleConstant.PASSWORD_VISITOR);
			userRoleDetail.addRole(RoleConstant.ROLE_VISITOR);
			SimpleAuthentication b = new SimpleAuthentication(RoleConstant.USER_VISITOR, RoleConstant.PASSWORD_VISITOR,
					userRoleDetail, null);
			SecurityContextHolder.getContext().setAuthentication(b);
		}
		chain.doFilter(request, response);
	}

}
